<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-18
 * Time: 13:59
 */

namespace app\manage\admin;

use app\admin\controller\Admin;
use app\admin\model\Access as AccessModel;
use app\admin\model\Module as ModuleModel;
use app\common\builder\ZBuilder;

// 引入ZBuilder
use app\common\model\Post as PostModel;
use app\user\model\Role as RoleModel;
use app\user\model\User as UserModel;
use think\Db;
use util\Tree;

class Post extends Admin
{
    //团队列表
    public function index($team_id = 1)
    {
        $topData = Db::name('qt_group')->whereIn('pid', ['0', '1'])->where('status', 1)->order('sort asc id desc')->select();
        $list = Db::name('qt_post')->field('id,title as name,team_id,post_pid as pid,post_step,sort,status')->where('team_id', $team_id)->select();
        $data = $this->getNestMenu($list, 0, '0', '1', $team_id);
        return view('post/index', ['menus' => $data, 'top_data' => $topData, 'team_id' => $team_id]);
    }

    /**
     * 新增岗位
     * @param string $group_id 所属团队ID
     * @return mixed
     * @throws \Exception
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function add($team_id = '', $post_id = '')
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');

            // 验证
            $result = $this->validate($data, 'Post.add');
            // 验证失败 输出错误信息
            if (true !== $result) $this->error($result);
            // 顶部节点url检查
            if (PostModel::create($data)) {
                $this->success('新增成功', url('index', ['team_id' => $team_id]));
            } else {
                $this->error('新增失败');
            }
        }
        $teamRes = Db::name('qt_group')->whereIn('pid', ['0', '1'])->where('status', 1)->order('sort asc id desc')->column('name', 'id');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增岗位')
            ->addHidden('team_id', $team_id)
            ->addFormItems([
                ['select', 'team_id', '所属公司', '所属公司', $teamRes, $team_id],
            ])
            ->addFormItems([
                ['select', 'post_pid', '所属上级岗位', '所属上级岗位', PostModel::getMenuTree(0, '顶级岗位', $team_id), $post_id],
            ])
            ->addFormItem(
                'text',
                'title',
                '岗位名称'
            )
            ->addText('post_step', '岗位等级', '<code>岗位等级1-32级</code>')
            ->addText('post_money', '岗位薪资', '<code>单位：元</code>')
            ->addText('sort', '排序', '<code>越小越靠前</code>', 50)
            ->addUeditor('content', '岗位描述')
            ->addRadio('default', '默认岗位', '<code>默认岗位为当前部门，员工刚入职的最低岗位</code>', ['2' => '否', '1' => '是'], '2')
            ->addRadio('status', '状态', '', ['1' => '正常', '2' => '禁用'], '1')
            ->fetch();
    }


    /**
     * 删除节点
     * @param array $record 行为日志内容
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function delete($id = '')
    {

        $menu = PostModel::where('id', $id)->find();
        // 获取该节点的所有后辈节点id
        $menu_childs = PostModel::getChildsId($id);

        // 要删除的所有节点id
        $all_ids = array_merge([(int)$id], $menu_childs);
        // 删除节点
        if (PostModel::destroy($all_ids)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


    /**
     * 编辑节点
     * @return mixed
     * @throws \Exception
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function edit($id = 0)
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Post.add');
            // 验证失败 输出错误信息
            if (true !== $result) $this->error($result);
            // 顶部节点url检查
            if (PostModel::update($data)) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 获取数据
        $info = PostModel::get($id);
        $teamRes = Db::name('qt_group')->whereIn('pid', ['0', '1'])->where('status', 1)->order('sort   id desc')->column('name', 'id');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑岗位')
            ->addHidden('id', $id)
            ->addFormItems([
                ['select', 'team_id', '所属公司', '所属公司', $teamRes],
            ])
            ->addFormItems([
                ['select', 'post_pid', '所属上级岗位', '所属上级岗位', PostModel::getMenuTree(0, '顶级岗位')],
            ])
            ->addFormItem(
                'text',
                'title',
                '岗位名称'
            )
            ->addText('post_step', '岗位等级', '<code>岗位等级1-32级</code>')
            ->addText('post_money', '岗位薪资', '<code>单位：元</code>')
            ->addText('sort', '排序', '<code>越小越靠前</code>', 50)
            ->addUeditor('content', '岗位描述')
            ->addRadio('default', '默认岗位', '<code>默认岗位为当前部门，员工刚入职的最低岗位</code>', ['2' => '否', '1' => '是'], '2')
            ->addRadio('status', '状态', '', ['1' => '正常', '2' => '禁用'], '1')
            ->setFormData($info)
            ->fetch();

    }


    /**
     * 获取嵌套式节点
     * @param array $lists 原始节点数组
     * @param int $pid 父级id
     * @param int $max_level 最多返回多少层，0为不限制
     * @param int $curr_level 当前层数
     * @return string
     * @author 蔡伟明 <314013107@qq.com>
     */
    private function getNestMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1, $team_id = 1)
    {
        $result = '';
        foreach ($lists as $key => $value) {
            if ($value['pid'] == $pid) {
                $disable = $value['status'] == 0 ? 'dd-disable' : '';
                // 组合节点
                $result .= '<li class="dd-item dd3-item ' . $disable . '" data-id="' . $value['id'] . '">';
                $result .= '<div class="dd-handle dd3-handle">拖拽</div><div class="dd3-content">' . $value['name'];
                $result .= '<div class="action">';
                $result .= '<a href="' . url('add', ['post_id' => $value['id'], 'team_id' => $team_id]) . '" data-toggle="tooltip" data-original-title="新增子节点"><i class="list-icon fa fa-plus fa-fw"></i></a><a href="' . url('edit', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a><a href="' . url('work_config', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="设置考勤" ><i class="list-icon fa fa-times fa-cog"></i></a>';
                $result .= '<a href="' . url('access', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="设置日报" ><i class="list-icon fa fa-times fa-cog"></i></a><a href="' . url('delete', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                $result .= '</div>';

                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    // 下级节点
                    $children = $this->getNestMenu($lists, $max_level, $value['id'], $curr_level + 1, $team_id);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">' . $children . '</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }


    /**
     * 授权
     * @param string $module 模块名
     * @param int $uid 用户id
     * @param string $tab 分组tab
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function access($module = '', $id = '')
    {
        //if ($uid === 0) $this->error('缺少参数');
        $uid = 0;
        $tab = '';
        // 获取所有授权配置信息
        $list_module = ModuleModel::where('access', 'neq', '')
            ->where('access', 'neq', '')
            ->where('status', 1)
            ->column('name,title,access');


        if ($list_module) {
            // tab分组信息
            $tab_list = [];
            foreach ($list_module as $key => $value) {
                $list_module[$key]['access'] = json_decode($value['access'], true);
                // 配置分组信息
                $tab_list[$value['name']] = [
                    'title' => '岗位设置日报分类',
                    'url' => url('access', [
                        'module' => $value['name'],
                        'uid' => $uid
                    ])
                ];
            }
            $module = $module == '' ? current(array_keys($list_module)) : $module;
            $this->assign('tab_nav', [
                'tab_list' => $tab_list,
                'curr_tab' => $module
            ]);
            // 读取授权内容
            $access = $list_module[$module]['access'];
            foreach ($access as $key => $value) {
                $access[$key]['url'] = url('access', [
                    'module' => $module,
                    'uid' => $uid,
                    'tab' => $key
                ]);
            }
            // 当前分组
            $tab = $tab == '' ? current(array_keys($access)) : $tab;
            // 当前授权
            $curr_access = $access[$tab];
            if (!isset($curr_access['nodes'])) {
                $this->error('模块：' . $module . ' 数据授权配置缺少nodes信息');
            }
            $curr_access_nodes = $curr_access['nodes'];
            $this->assign('tab', $tab);
            $this->assign('access', $access);
            if ($this->request->isPost()) {
                $post = $this->request->param();
                if (isset($post['nodes'])) {
                    $data_node = [];
                    $teamId = Db::name('qt_post')->where('id', $post['post_id'])->value('team_id');
                    foreach ($post['nodes'] as $node) {
                        list($group, $dailyId) = explode('|', $node);
                        $data_node[] = [
                            'team_id' => $teamId,
                            'post_id' => $post['post_id'],
                            'daily_type_id' => $dailyId,
                        ];
                    }
                    // 先删除原有授权
                    if (false === Db::name('qt_post_daily')->where('post_id',$post['post_id'])->delete()) {
                        $this->error('清除旧授权失败');
                    }
                    // 添加新的授权
                    $insert = Db::name('qt_post_daily')->insertAll($data_node);
                    if (!$insert) {
                        $this->error('操作失败');
                    }
                    $this->success('操作成功', url('access', ['id' => $post['post_id']]));
                } else {
                    // 清除所有数据授权
                    if (false === Db::name('qt_post_daily')->where('post_id',$post['post_id'])->delete()) {
                        $this->error('清除旧授权失败');
                    } else {
                        $this->success('操作成功');
                    }
                }
            } else {
                // 没有设置模型名，则按表名获取数据
                $fields = ['id', 'pid', 'name'];
                $nodes = Db::name('qt_daily_type')->where('global','2')->order('id')->field($fields)->select();
                $tree_config = [
                    'title' => 'name',
                    'id' => 'id',
                    'pid' => 'pid'
                ];
                $nodes = Tree::config($tree_config)->toLayer($nodes);
                //dump($nodes);die;
                // 查询当前用户的权限
                $map = [
                    'module' => $module,
                    'tag' => $tab,
                    'uid' => $uid
                ];
                $node_access = Db::name('qt_post_daily')->where('post_id', $id)->select();
                $user_access = [];
                foreach ($node_access as $item) {
                    $user_access['task|' . $item['daily_type_id']] = 1;
                }
                $nodes = $this->buildJsTree($nodes, $curr_access_nodes, $user_access);
                $this->assign('nodes', $nodes);
            }
        }
        $teamRes = Db::name('qt_post')
            ->alias('p')
            ->leftJoin('qt_group g', 'p.team_id = g.id')
            ->field('p.title,g.name,g.id')
            ->where(['p.id' => $id])
            ->find();
        $this->assign('module', $module);
        $this->assign('uid', $uid);
        $this->assign('tab', $tab);
        $this->assign('page_title', $teamRes['name'] . '--' . $teamRes['title']);
        $this->assign('post_id', $id);
        $this->assign('team_id', $teamRes['id']);
        return $this->fetch();
    }

    /**
     * 设置考勤
     * @return mixed
     * @throws \think\Exception
     */
    public function work_config($id = ''){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            if(empty($data['work_id'])){
                $this->error('请选择打卡');
            }
            //删除打卡
            $del = Db::name('qt_post_work')->where('post_id',$data['post_id'])->delete();
            if($del !== 0 ){
                $this->error('服务器错误，请稍后重试');
            }
            // 顶部节点url检查
            if (Db::name('qt_post_work')->insert($data)) {
                $this->success('新增成功', url('index',['team_id'=>$data['team_id']]));
            } else {
                $this->error('新增失败');
            }
        }
        // 获取数据
        $info = Db::name('qt_post_work')->where(['post_id'=>$id])->find();
        $postRes = Db::name('qt_post')->where('id',$id)->find();
        $workRes = Db::name('qt_work')->where('group_id',$postRes['team_id'])->order('id desc')->column('name', 'id');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle($postRes['title'].'设置考勤')
            ->addHidden('post_id', $id)
            ->addHidden('team_id', $postRes['team_id'])
            ->addFormItems(
                [
                    ['radio:4', 'work_id', '考勤', '', $workRes],
                ]
            )


            //->addRadio('work_id', '考勤', '', $workRes)
            ->setFormData($info)
            ->fetch();
    }



    /**
     * 构建jstree代码
     * @param array $nodes 节点
     * @param array $curr_access 当前授权信息
     * @param array $user_access 用户授权信息
     * @return string
     * @author 蔡伟明 <314013107@qq.com>
     */
    private function buildJsTree($nodes = [], $curr_access = [], $user_access = [])
    {
        $result = '';
        if (!empty($nodes)) {
            $option = [
                'opened' => true,
                'selected' => false
            ];
            foreach ($nodes as $node) {

                $key = $curr_access['group'] . '|' . $node[$curr_access['primary_key']];
                $option['selected'] = isset($user_access[$key]) ? true : false;
                if (isset($node['child'])) {
                    $curr_access_child = isset($curr_access['child']) ? $curr_access['child'] : $curr_access;
                    $result .= '<li id="' . $key . '" data-jstree=\'' . json_encode($option) . '\'>' . $node['name'] . $this->buildJsTree($node['child'], $curr_access_child, $user_access) . '</li>';
                } else {
                    $result .= '<li id="' . $key . '" data-jstree=\'' . json_encode($option) . '\'>' . $node['name'] . '</li>';
                }
            }
        }

        return '<ul>' . $result . '</ul>';
    }

    /**
     * 获取嵌套式节点
     * @param array $lists 原始节点数组
     * @param int $pid 父级id
     * @param int $max_level 最多返回多少层，0为不限制
     * @param int $curr_level 当前层数
     * @return string
     * @author 蔡伟明 <314013107@qq.com>
     */
    private function getGroupMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1)
    {
        $result = '';
        foreach ($lists as $key => $value) {
            if ($value['pid'] == $pid) {
                $disable = $value['status'] == 0 ? 'dd-disable' : '';
                // 组合节点
                $result .= '<li class="dd-item dd3-item ' . $disable . '" data-id="' . $value['id'] . '">';
                $result .= '<div class="dd-handle dd3-handle">拖拽</div><div class="dd3-content">' . $value['name'];
                $result .= '<div class="action">';
                if ($curr_level <= 2) {
                    $result .= '<a href="' . url('add', ['pid' => $value['id']]) . '" data-toggle="tooltip" data-original-title="新增团队"><i class="list-icon fa fa-plus fa-fw"></i></a><a href="' . url('edit', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                    $result .= '<a href="' . url('delete', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                } else {
                    $result .= '<a href="' . url('edit', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                    $result .= '<a href="' . url('delete', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                }
                $result .= '</div>';
                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    // 下级节点
                    $children = $this->getGroupMenu($lists, $max_level, $value['id'], $curr_level + 1);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">' . $children . '</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }


    /**
     * 获取当前团队下面的岗位
     * @param $team_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_post($team_id)
    {
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $data = Db::name('qt_post')->where('team_id', $team_id)->field('id,title')->select(); //数据
        $result = [];
        foreach ($data as $key => $value) {
            $result[$key]['key'] = $value['id'];
            $result[$key]['value'] = $value['title'];
        }
        $arr['list'] = $result;
        return json($arr);
    }


}